package org.jjj.basic.controller;

import org.apache.commons.io.FilenameUtils;
import org.jjj.basic.service.IFastDfsService;
import org.jjj.basic.utils.ResultAjax;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastdfs")
public class FastdfsController {
    @Autowired
    private IFastDfsService fastDfsService;

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping
    public ResultAjax upload(MultipartFile file){
        try {
            //获取文件的字节流
            byte[] bytes = file.getBytes();
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //获取后缀名
            String extName = FilenameUtils.getExtension(originalFilename);
            //上传成功返回地址
            String path = fastDfsService.upload(bytes,extName);
            return ResultAjax.me().setResult(path);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultAjax.me().setSuccess(false).setMessage(e.getMessage());
        }
    }

    /**
     * 删除文件
     * @param path
     * @return
     */
    @DeleteMapping
    public ResultAjax delete(String path){
        try {
            fastDfsService.delete(path);
            return ResultAjax.me();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultAjax.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
}
